package com.fenda.mybleapplication;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.SavedStateViewModelFactory;
import androidx.lifecycle.ViewModelProvider;

import android.content.Intent;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.widget.ImageButton;
import android.widget.TextView;

import com.fenda.mybleapplication.databinding.ActivityMainBinding;
import com.fenda.mybleapplication.study.ViewModelWithLiveData;
import com.fenda.mybleapplication.study.page.ViewModelActivity;

public class MainActivity extends AppCompatActivity {
    ViewModelWithLiveData viewModelWithLiveData;

    //加入DataBinding之后这些不需要  MVVC开发模式
//    TextView tv1;
//    ImageButton imageView1,imageView2;


    ActivityMainBinding binding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        setContentView(R.layout.activity_main);

        binding = DataBindingUtil.setContentView(MainActivity.this,R.layout.activity_main);
        //viewModel实例之二
//        viewModelWithLiveData = new ViewModelProvider(this,new ViewModelProvider.NewInstanceFactory()).get(ViewModelWithLiveData.class);

        //增加SavedStateHandle
        viewModelWithLiveData = new ViewModelProvider(this,new SavedStateViewModelFactory(getApplication(),this)).get(ViewModelWithLiveData.class);

//        viewModelWithLiveData = ViewModelProvider.AndroidViewModelFactory
//                .getInstance(this.getApplication()).create(ViewModelWithLiveData.class);


        //viewModel实例之二
//        viewModelWithLiveData = new ViewModelProvider(this,new ViewModelProvider.NewInstanceFactory()).get(ViewModelWithLiveData.class);


        //插入viewModel
        binding.setData(viewModelWithLiveData);
        //观察
        binding.setLifecycleOwner(this);
        //观察者模式 ,使用DataBinding后注释,这个是LiveData下来单项观察数据
//        viewModelWithLiveData.getLikedNumber().observe(this, integer -> {
//            binding.tv1.setText(String.valueOf(integer));
//        });


        //xml中也可以直接写表达式,进行数据viewModel双向绑定
        binding.imageView.setOnClickListener(view -> {
            viewModelWithLiveData.addLikedNumber(1);
        });
        binding.button.setOnClickListener( v -> {
            startActivity(new Intent(this, ViewModelActivity.class));
        });


    }

    @Override
    public void onSaveInstanceState(@NonNull Bundle outState, @NonNull PersistableBundle outPersistentState) {
        super.onSaveInstanceState(outState, outPersistentState);
        //一般用来保存杀死之前的数据 然后在OnCreate中调用savedInstanceState取出
        //系统杀死 可使用import androidx.lifecycle.SavedStateHandle;
    }
}